<template>
  <div class="courses-page">
    <el-card shadow="never" v-loading="loading" element-loading-text="加载中...">
      <div slot="header" class="card-header">
        <div>
          <h3 class="title">课程列表</h3>
          <p class="subtitle">所有焊接相关课程</p>
        </div>
        
        <div class="header-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索课程..."
            prefix-icon="el-icon-search"
            size="small"
            clearable
            style="width: 200px;"
            @keyup.enter.native="handleSearch"
          ></el-input>
          
          <el-select
            v-model="filterType"
            placeholder="全部类型"
            size="small"
            clearable
            style="width: 120px;"
          >
            <el-option label="全部类型" value="all"></el-option>
            <el-option label="理论课程" value="theory"></el-option>
            <el-option label="实践课程" value="practice"></el-option>
            <el-option label="选修课程" value="elective"></el-option>
          </el-select>

          <el-button 
            type="primary" 
            size="small"
            icon="el-icon-search"
            @click="handleSearch"
          >
            搜索
          </el-button>

          <el-button 
            size="small"
            icon="el-icon-refresh"
            @click="handleReset"
          >
            重置
          </el-button>
        </div>
      </div>

      <el-table :data="filteredCourses" style="width: 100%;">
        <el-table-column label="课程名称" min-width="180">
          <template slot-scope="scope">
            <span style="font-weight: 500;">{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="类型" width="90">
          <template slot-scope="scope">
            <el-tag 
              :type="getTypeTagType(scope.row.type)" 
              size="small"
            >
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="内容" width="80" prop="contentCount" align="center"></el-table-column>

        <el-table-column label="测验" width="80" prop="quizCount" align="center"></el-table-column>

        <el-table-column label="状态" width="90">
          <template slot-scope="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.status)" 
              size="small"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="学习进度" min-width="150">
          <template slot-scope="scope">
            <div class="progress-cell">
              <span class="progress-text">{{ scope.row.progress }}%</span>
              <el-progress 
                :percentage="scope.row.progress" 
                :show-text="false"
                :stroke-width="6"
              ></el-progress>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              @click="gotoCourseDetail(scope.row.id)"
            >
              {{ scope.row.status === '已完成' ? '复习' : (scope.row.status === '进行中' ? '继续学习' : '开始学习') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <div class="pagination-info">
          显示 {{ (currentPage - 1) * pageSize + 1 }} 至 {{ Math.min(currentPage * pageSize, totalCourses) }} 条，共 {{ totalCourses }} 条
        </div>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalCourses"
          :page-size="pageSize"
          :current-page.sync="currentPage"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Courses',
  data() {
    return {
      searchKeyword: '',
      filterType: 'all',
      currentPage: 1,
      pageSize: 10,
      totalCourses: 0,
      allCourses: [],
      loading: false
    }
  },
  mounted() {
    this.getCourseList()
  },
  watch: {
    currentPage() {
      this.getCourseList()
    }
  },
  computed: {
    filteredCourses() {
      let courses = this.allCourses

      // 类型筛选
      if (this.filterType !== 'all') {
        const typeMap = {
          'theory': '理论课程',
          'practice': '实践课程',
          'elective': '选修课程'
        }
        courses = courses.filter(c => c.type === typeMap[this.filterType])
      }

      // 关键词搜索
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        courses = courses.filter(c => 
          c.name.toLowerCase().includes(keyword) || 
          c.number.toLowerCase().includes(keyword)
        )
      }

      return courses
    }
  },
  methods: {
    // 获取课程列表
    async getCourseList() {
      this.loading = true
      try {
        const res = await this.$api.course.getCourseList({
          page: this.currentPage,
          page_size: this.pageSize
        })
        
        
        // 后端返回分页数据: { data: [...], pagination: {total, page, page_size, last_page} }
        this.allCourses = (res.data || []).map(course => {
          const progress = course.progress || 0
          return {
            id: course.id,
            name: course.name,
            number: course.code || '',
            type: course.category?.name || '理论课程', // 后端返回 category 对象
            contentCount: course.knowledge_count || 0,
            quizCount: course.paper_count || 0,
            status: this.mapCourseStatus(progress), // 根据进度计算状态
            progress: progress // 使用后端返回的进度
          }
        })
        
        // 更新总数
        this.totalCourses = res.pagination?.total || this.allCourses.length
      } catch (error) {
        this.$message.error('获取课程列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 映射课程类型
    mapCourseType(categoryName) {
      if (!categoryName) return '理论课程'
      if (categoryName.includes('实践') || categoryName.includes('实训')) {
        return '实践课程'
      } else if (categoryName.includes('选修')) {
        return '选修课程'
      }
      return '理论课程'
    },
    
    // 映射课程状态
    mapCourseStatus(progress) {
      if (progress >= 100) return '已完成'
      if (progress > 0) return '进行中'
      return '未开始'
    },
    
    handleSearch() {
      this.currentPage = 1
      this.getCourseList()
    },
    
    handleReset() {
      this.searchKeyword = ''
      this.filterType = 'all'
      this.currentPage = 1
      this.getCourseList()
      this.$message.success('已重置搜索条件')
    },
    getTypeTagType(type) {
      const typeMap = {
        '理论课程': '',
        '实践课程': 'success',
        '选修课程': 'warning'
      }
      return typeMap[type] || ''
    },
    getStatusTagType(status) {
      const statusMap = {
        '进行中': '',
        '已完成': 'success',
        '未开始': 'info'
      }
      return statusMap[status] || ''
    },
    gotoCourseDetail(id) {
      this.$router.push(`/course/${id}`)
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #304156;
  margin: 0 0 4px 0;
}

.subtitle {
  font-size: 13px;
  color: #86909C;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.header-actions .el-input {
  width: 200px;
}

.header-actions .el-select {
  width: 120px;
}

.progress-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.progress-text {
  font-size: 13px;
  color: #606266;
}

.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #EBEEF5;
}

.pagination-info {
  font-size: 13px;
  color: #86909C;
}

@media (max-width: 992px) {
  .card-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    flex-direction: column;
  }
  
  .header-actions .el-input,
  .header-actions .el-select,
  .header-actions .el-button {
    width: 100% !important;
  }
  
  .pagination-wrapper {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
